package com.heima.wemedia.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author zhouao
 * @date 2022/06/14
 */
@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {


    /**
     * 条件查询
     *
     * @param dto
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //若没有传递参数直接放回错误
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        Integer id = WmThreadLocalUtil.getUser().getId();
        //若用户未登陆直接返回错误
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //查询条件
        LambdaQueryWrapper<WmNews> query = Wrappers.<WmNews>lambdaQuery();
        //验证分页
        dto.checkParam();
        //查询当前用户下的文章
        query.eq(WmNews::getUserId, id);
        //若时间参数不为空则加上参数
        if (dto.getBeginPubdate() != null && dto.getEndPubdate() != null) {
            query.between(WmNews::getPublishTime, dto.getBeginPubdate(), dto.getEndPubdate());
        }
        //若频道参数不为空则加上
        if (dto.getChannelId() != null) {
            query.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //如果文本框不为空则按照关键字查询
        if (dto.getKeyword() != null) {
            query.like(WmNews::getTitle, dto.getKeyword());
        }
        //按照时间排序
        query.orderByDesc(WmNews::getCreatedTime);
        //执行查询
        Page page = new Page(dto.getPage(), dto.getSize());
        Page page1 = this.page(page, query);
        //封装数据
        PageResponseResult result = new PageResponseResult();
        result.setTotal((int) page1.getTotal());
        result.setSize((int) page1.getSize());
        result.setCurrentPage(dto.getPage());
        result.setData(page1.getRecords());
        return result;
    }
}